//
//  AuthServiceProtocol.swift
//  
//
//  Created by tank on 2021/11/17.
//

import Foundation
import LibBase

public enum LoginResult: Int {
    // 登录成功
    case success
    // 登录错误
    case error
    // 已登录
    case logged
}

public protocol AuthServiceProtocol: AnyObject {
    typealias LoginCompletion = (_ loginResult: LoginResult, _ message: String?) -> Void
    
    var authRepository: AuthRepository { get }
    
    /// 登录
    func login(completion: LoginCompletion?)
    
    /// 登出
    func logout()
    
    /// 更新token、refreshToken等信息
    func update(accessToken: String, refreshToken: String, expiredTime: Date)
    
    /// 未认证
    func unauthorized(message: String?)
}

public extension AuthServiceProtocol {
    var authRepository: AuthRepository {
        return DataRepositoryManager.shared.repository(id: AuthRepository.id) as! AuthRepository
    }
    
    func update(accessToken: String, refreshToken: String, expiredTime: Date) {
        authRepository.update(accessToken: accessToken,
                              refreshToken: refreshToken,
                              expiredTime: expiredTime)
    }
    
    func unauthorized(message: String?) {
        authRepository.set(data: nil)
        
        ServiceManager.shared
            .routerService?
            .alert(dialogId: "unauthorized",
                   title: "提示",
                   message: message ?? "unauthorized",
                   confirmButtonText: "重新登录",
                   interactive: false) { [weak self] buttonId in
                guard buttonId != nil else {
                    return
                }
                
                _ = ServiceManager.shared.routerService?.push(url: "app://page/root", animated: false)
                self?.login(completion: nil)
            }
    }
}
